package com.quan.system.web.controller;

import com.alibaba.fastjson.JSON;
import com.quan.commons.core.MyBaseController;
import com.quan.commons.vo.R;
import com.quan.system.commons.vo.WebSocketMessageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * WebSocket 前端控制器
 * 提供给前端调用
 *
 * @author yhaoquan
 */
@Slf4j
@RestController
@RequestMapping("/websocket")
public class WebSocketSockJSController extends MyBaseController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 前端SockJS连接，成功返回信息给客户端
     *
     * @return
     */
    @SubscribeMapping(value = "connect")
    public String connect() {
        return "欢迎订阅【系统消息功能】";
    }

    /**
     * 广播系统消息
     *
     * @param message
     */
    @PostMapping("sendSystemBroadcastMessage")
    public R sendSystemBroadcastMessage(@RequestBody WebSocketMessageVo message) {
        log.info("WebSocket 发送系统消息：{}", message);

        // 标识消息来自系统
        message.setFrom("system");

        this.messagingTemplate.convertAndSend("/server/system/broadcast", JSON.toJSONString(message));
        return R.ok("消息已发送");
    }

    /**
     * 给指定用户发送消息
     *
     * @param message
     */
    @PostMapping("sendMessageToUser")
    public R sendMessageToUser(@RequestBody WebSocketMessageVo message) {
        log.info("WebSocket 给用户发送消息：{}", message);

        if (null != message.getTo() && !message.getTo().isEmpty()) {
            for (String to : message.getTo()) {
                this.messagingTemplate.convertAndSendToUser(to, "/message", JSON.toJSONString(message));
            }
            return R.ok("消息已发送");
        } else {
            return R.failure("消息发送失败");
        }
    }

}
